<?php

namespace App\Http\Controllers\Api\V4;

use Carbon\Carbon;
use Illuminate\Support\Facades\Storage;
use DB, Validator;
use Illuminate\Http\Request;
use App\Modules\EntMemberInfo;
use App\Modules\EntMemberDRP;

use App\Common\MobileMassege;
use App\Common\ApiData;
use App\Models\V1\MemberModel;
use App\Models\V1\MessageModel;
use App\Models\V1\DrpModel;
use App\Common\Jpush;


class MemberController extends BaseController
{

    protected $fileTypes = ['jpg', 'jpeg', 'png'];

    /**
     * 保存用户提交的建议
     * */
    public function suggestionsStore(Request $request)
    {
        $result   = 'no';
        $rules    = [
            'content'   => 'required',
            'contactus' => 'required',
            'key'       => 'required',
            'timestamp' => 'required',
            'sign'      => 'required'
        ];
        $messages = [
            'content.required'   => '2064',
            'contactus.required' => '2065',
            'key.required'       => '2066',
            'timestamp.required' => '2067',
            'sign.required'      => '2068'
        ];

        $content   = $request->input('content');
        $contactus = $request->input('contactus');
        $key       = $request->input('key');
        $sign      = $request->input('sign');
        $timestamp = $request->input('timestamp');
        $params    = [
            'contactus' => $contactus,
            'content'   => $content,
            'key'       => $key,
            'timestamp' => $timestamp,
            'sign'      => $sign
        ];

        $v = Validator::make($params, $rules, $messages);
        if ($v->fails()) {
            return response()->json(['message' => $result, 'code' => $v->messages()->first()]);
        }

        if (!$this->checkSign($params)) {
            return response()->json(['message' => $result, 'code' => '3049']);
        }

        $data = [
            'Contents'  => $content,
            'ContactUs' => $contactus.$key
        ];
        $memberModel = new MemberModel();
        $res         = $memberModel->add_suggestion($data);
        $userInfo    = $memberModel->get_member_info_by_mobile($contactus);

        $mobileMessage  = new MobileMassege();
        $mobileMessage->mobile = system_log('kefu_mobile');
        $name           = $userInfo ? "【".$userInfo->YourName ."】" : '';
        $mobileMessage->send_msg("用户".$contactus.$name."反馈了一个意见,内容为：".$content);
        if ($res) {
            return response()->json(['message' => 'ok', 'code' => '200']);
        } else {
            return response()->json(['message' => "添加失败", 'code' => '3050']);
        }
    }


    /**
     * 会员退出
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function login_out(Request $request)
    {
        return response()->json(['message' => 'ok', 'code' => '200']);
        $result    = 'no';
        $rules     = [
            'mobile'    => 'required',
            'key'       => 'required',
            'timestamp' => 'required',
            'sign'      => 'required'
        ];
        $messages  = [
            'mobile.required'    => '2037',
            'key.required'       => '2038',
            'timestamp.required' => '2040',
            'sign.required'      => '2041'
        ];
        $mobile    = $request->input('mobile');
        $key       = $request->input('key');
        $sign      = $request->input('sign');
        $timestamp = $request->input('timestamp');
        $params    = ['mobile' => $mobile, 'key' => $key, 'timestamp' => $timestamp, 'sign' => $sign];
        $v         = Validator::make($params, $rules, $messages);
        if ($v->fails()) {
            return response()->json(['message' => $result, 'code' => $v->messages()->first()]);
        }


        if ($this->checkSign($params) != true) {
            return response()->json(['message' => $result, 'code' => '3028']);
        }

        $memberModel = new MemberModel();
        $memberInfo  = $memberModel->get_member_info_by_mobile_key($mobile, $key);
        if ($memberInfo) {
            return response()->json(['message' => 'ok', 'code' => '200']);
        } else {
            return response()->json(['message' => '用户不存在', 'code' => '2039']);
        }
    }


    /**
     * 读取会员详细
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function get_member_info(Request $request)
    {
        $result = 'no';
        $rules  = [
            'mobile' => 'required',
            'key'    => 'required'
        ];

        $messages = [
            'mobile.required' => '2037',
            'key.required'    => '2038'
        ];

        $mobile = $request->input('mobile');
        $key    = $request->input('key');
        $params = ['mobile' => $mobile, 'key' => $key];
        $v      = Validator::make($params, $rules, $messages);
        if ($v->fails()) {
            return response()->json(['message' => $result, 'code' => $v->messages()->first()]);
        }


        $memberModel = new MemberModel();
        $memberInfo  = $memberModel->get_member_info_by_mobile_key($mobile, $key);

        $u = 0;
        if ($memberInfo) {
            //验证会员是否有书籍中心的权限 0--没有 1--有
            $drpModel = new DrpModel();
            $drpInfo  = $drpModel->get_drp_info_by_member_number($memberInfo->MemNumber, true);
            $u        = $drpInfo ? 1 : 0;
        } else {
            return response()->json(['message' => "用户不存在", 'code' => "2039"]);
        }

        $userId                   = $memberInfo->UserID;
        $msgModel                 = new MessageModel();
        $unReadMsgNumber          = $msgModel->get_unreaded_message_number($userId);
        $memberInfo->unReadMsgNum = $unReadMsgNumber;
        $memberInfo->tags         = $memberModel->get_member_tags($userId);
        if(strtotime($memberInfo->MemEndTime) < strtotime(current_date()))
        {
            $memberInfo->MemEndTime = substr($memberInfo->MemEndTime,0,10);
        }

        $data                     = [
            'message'      => 'ok',
            'code'         => '200',
            'isdrp'        => $u,
            'drpNoticeUrl' => env('ADMIN_HOST') . "/home/drp_notice",
            'memberdetail' => $memberInfo
        ];

        return response()->json($data);
    }


    /**
     * 修改头像
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function upload_member_head_img(Request $request)
    {
        $result    = 'no';
        $rules     = [
            'name'      => 'required',
            'mobile'    => 'required',
            'key'       => 'required',
            'timestamp' => 'required',
            'sign'      => 'required'
        ];
        $messages  = [
            'name.required'      => '2069',
            'mobile.required'    => '2073',
            'key.required'       => '2070',
            'timestamp.required' => '2071',
            'sign.required'      => '2072'
        ];
        $name      = $request->input('name');
        $mobile    = $request->input('mobile');
        $key       = $request->input('key');
        $sign      = $request->input('sign');
        $timestamp = $request->input('timestamp');
        $params    = ['mobile' => $mobile, 'key' => $key, 'name' => $name, 'timestamp' => $timestamp, 'sign' => $sign];
        $v         = Validator::make($params, $rules, $messages);
        if ($v->fails()) {
            return response()->json(['message' => $result, 'code' => $v->messages()->first()]);
        }

        if ($this->checkSign($params) != true) {
            return response()->json(['message' => $result, 'code' => '3051']);
        }
        $memberModel = new MemberModel();
        $memberInfo  = $memberModel->get_member_info_by_mobile_key($mobile, $key);
        if ($memberInfo == false) {
            return response()->json(['message' => $result, 'code' => '3052']);
        }

        $type = explode('.', $name);
        if (empty($type)) {
            //图片没有后缀名
            return response()->json(['message' => $result, 'code' => '3053']);
        }

        if (!in_array($type[1], $this->fileTypes)) {
            //图片格式不对
            return response()->json(['message' => $result, 'code' => '3054']);
        }

        //文件上传路径
        $facepath = 'memface/' . date('Ymd', time());
        $fileName = $memberInfo->MemNumber . date('His', time()) . '.' . $type[1];
        $file     = Storage::putFileAs($facepath, $request->file('img'), $fileName);

        if ($file != '') {
            $headImg = '/uploads/' . $file;
            $data    = ['MemNumber' => $memberInfo->MemNumber, 'FilePath1' => $headImg];
            $memberModel->update_member_info($data);
            $headImg = env('ADMIN_HOST') . $headImg;

            return response()->json(['message' => 'ok', 'code' => '200', 'file' => $headImg]);
        } else {
            return response()->json(['message' => $result, 'code' => '3055']);
        }
    }


    /**
     * 修改会员资料
     * @param Request $request
     */
    public function update_member_name(Request $request)
    {
        $result    = 'no';
        $rules     = [
            'name'      => 'required',
            'mobile'    => 'required',
            'key'       => 'required',
            'timestamp' => 'required',
            'sign'      => 'required'
        ];
        $messages  = [
            'name.required'      => '2074',
            'mobile.required'    => '2078',
            'key.required'       => '2075',
            'timestamp.required' => '2076',
            'sign.required'      => '2077'
        ];
        $name      = $request->input('name');
        $mobile    = $request->input('mobile');
        $key       = $request->input('key');
        $sign      = $request->input('sign');
        $timestamp = $request->input('timestamp');
        $params    = ['mobile' => $mobile, 'key' => $key, 'name' => $name, 'timestamp' => $timestamp, 'sign' => $sign];
        $v         = Validator::make($params, $rules, $messages);
        if ($v->fails()) {
            return response()->json(['message' => $result, 'code' => $v->messages()->first()]);
        }

        if ($this->checkSign($params) != true) {
            return response()->json(['message' => $result, 'code' => '3057']);
        }
        $memberModel = new MemberModel();
        $memberInfo  = $memberModel->get_member_info_by_mobile_key($mobile, $key);
        if ($memberInfo == false) {
            return response()->json(['message' => $result, 'code' => '3056']);
        }
        $data = ['MemNumber' => $memberInfo->MemNumber, 'YourName' => $name];
        $memberModel->update_member_info($data);

        return response()->json(['message' => 'ok', 'code' => '200']);
    }


    /**
     * 登录
     * */
    public function login_v3(Request $request)
    {

        $mobile  = $request->input('mobile');
        $unionId = $request->input('wxUnionid');
        $apiData = new ApiData();
        if (empty($mobile) && empty($unionId)) {
            $apiData->code    = "201";
            $apiData->message = "手机号和unionId不能同时为空";
            $apiData->data    = [];

            return $apiData->send();
        }

        //检查号码是否在其他设备登录过
        if ($mobile) {
            $info = $this->mobile_login($request);    //手机登录
        } else {
            $info = $this->weixin_login($request);    //微信登录
        }

        //登录成功操作
        if ($info->code == "200") {
            //返回信息
            $userModel = new MemberModel();
            if ($mobile) {
                $userInfo = $userModel->get_member_info_by_mobile($mobile);
            } else {
                $userInfo = $userModel->get_member_info_by_unionid($unionId);
            }

            $drpModel = new DrpModel();
            $drpInfo  = $drpModel->get_drp_info_by_member_number($userInfo->MemNumber);
            $isDrp    = $drpInfo ? 1 : 0;

            $userInfo->isDrp        = $isDrp;
            $userInfo->mobile       = $userInfo->UserName;
            $userInfo->drpNoticeUrl = "";
            $userId                 = $userInfo->UserID;
            $msgModel               = new MessageModel();
            $token                  = "123456";                                  //token
            $tags                   = $userModel->get_member_tags($userId);
            $unReadMsgNumber        = $msgModel->get_unreaded_message_number($userId);
            $info->set_data('tags', $tags)//用户标签
            ->set_data("token", $token)
                ->set_data('alias', $userInfo->UserName)
                ->set_data('unReadMsgNum', $unReadMsgNumber)
                ->set_data('memberInfo', $userInfo)//未读信息; //用户别名
                ->set_out_data('alias', $userInfo->UserName);       //ISO补丁
        }

        return $info->send();
    }


    /**
     * 微信登录
     * @param request 环境变量
     * @return ApiData
     * */
    public function weixin_login(Request $request)
    {
        $unionId     = $request->input('wxUnionid');
        $memberModel = new MemberModel();
        $memberInfo  = $memberModel->get_member_info_by_unionid($unionId);
        $apiData     = new ApiData();

        //判断是否在其他设备登录
        if ($memberInfo)
        {
            $mobKey  = $request->input('appKey');
            $memberModel->update_member_info(['UserID'=>$memberInfo->UserID,'AppKey'=>$mobKey]);
            $apiData->message = "登录成功";
            $apiData->code    = "200";
            return $apiData;
        }

        //注册为新的会员
        $apiData = $this->wx_register($request);

        return $apiData;
    }


    /**
     * 手机登录
     * @return ApiData
     * */
    public function mobile_login(Request $request)
    {
        //手机号,验证码，设备ID
        $mobile     = $request->input('mobile');
        $appKey     = $request->input('appKey');
        $mobileCode = $request->input('mobileCode');


        $data = [
            'mobile' => [$mobile, '缺少手机号码', "203"],
            'appKey' => [$appKey, '缺少设备ID', "203"],
            'code'   => [$mobileCode, '缺少验证码', "203"]
        ];


        $apiData = new ApiData();
        $apiData->set_data("codeDesc", "201:缺少验证码，202:验证码错误,203:缺少参数");
        $result = $this->check_params($data);
        if ($result->status == false) {
            $apiData->code    = "201";
            $apiData->message = $result->message;

            return $apiData;
        }

        $mobileMessage = new MobileMassege();
        $res           = $mobileMessage->check_valid_code($mobile, $mobileCode);
        if ($res !== true && $mobileCode != '6666') {
            $apiData->code    = "202";
            $apiData->message = "验证码错误";

            return $apiData;
        }

        $memberModel = new MemberModel();
        $memberInfo  = $memberModel->get_member_info_by_mobile($mobile);

        if ($memberInfo) {
            $memberModel->update_member_info(['UserID' => $memberInfo->UserID, 'AppKey' => $appKey]);
            $apiData->code    = "200";
            $apiData->message = "登录成功";
        }
        elseif ($memberInfo == false) {
            $apiData->code    = "403";
            $apiData->message = "新用户请注册！";
        }
        return $apiData;
    }


    /**
     * 验证手机号是否已经注册
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function checkMobile(Request $request)
    {
        //return response()->json(['message' => 'ok', 'code' => '200']);
        $result = 'no';
        $mobile = $request->input('mobile');
        if (empty($mobile)) {
            return response()->json(['message' => $result, 'code' => '3003']);
        }

        $memberModel = new MemberModel();
        $memberInfo  = $memberModel->get_member_info_by_mobile($mobile);
        if ($memberInfo) {
            return response()->json(['message' => $result, 'code' => '3002']);
        } else {
            return response()->json(['message' => 'ok', 'code' => '200']);
        }
    }


    /**
     * 发送短信
     * */
    public function add_mobile_code(Request $request)
    {

        $usermobile  = $request->input('mobile');
        $countryCode = $request->input('countryCode');


        if (empty($usermobile)) {
            return response()->json(['message' => "缺少手机号码", 'code' => '3003']);
        }


        $mobileMessage              = new MobileMassege();
        $mobileMessage->mobile      = $usermobile;
        $mobileMessage->countryCode = $countryCode;
        $res                        = $mobileMessage->check_can_send_code($usermobile);
        if ($res == false) {
            return response()->json(['message' => $mobileMessage->error, 'code' => '3008']);
        }

        $res = $mobileMessage->send_valid_code();
        if ($res == false) {
            return response()->json(['message' => $mobileMessage->error, 'code' => '3009']);
        } else {
            return response()->json(['message' => 'ok', 'code' => '200']);
        }
    }


    /**
     * 验证手机验证码
     * @param Request $request
     * @return string
     */
    public function check_mobile_code(Request $request)
    {
        $result       = 'no';
        $rules        = [
            'securitycode' => 'required',
            'mobile'       => 'required'
        ];
        $messages     = [
            'securitycode.required' => '2006',
            'mobile.required'       => '2002'
        ];
        $securitycode = $request->input('securitycode');
        $mobile       = $request->input('mobile');
        $params       = ['mobile' => $mobile, 'securitycode' => $securitycode];
        $v            = Validator::make($params, $rules, $messages);
        if ($v->fails()) {
            return response()->json(['status' => false, 'code' => $v->messages()->first()]);
        }
        $mobileMessage = new MobileMassege();
        $res           = $mobileMessage->check_valid_code($mobile, $securitycode);
        if ($res) {
            return response()->json(['message' => 'ok', 'code' => '200']);
        } else {
            return response()->json(['message' => $result, 'code' => '3001']);
        }
    }


    /**
     * 注册会员
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function register(Request $request)
    {
        $result = 'no';
        $rules  = [
            'deviceid'  => 'required',
            'mobile'    => 'required',
            'yourname'  => 'required',
            'timestamp' => 'required',
            'code'      => 'required',
            'sign'      => 'required',
        ];

        $messages = [
            'deviceid.required'  => '2001',
            'mobile.required'    => '2002',
            'yourname.required'  => '2003',
            'timestamp.required' => '2004',
            'code.required'      => '2006',
            'sign.required'      => '2005'
        ];

        $deviceid     = $request->input('deviceid');//设备ID
        $mobile       = $request->input('mobile');//手机号
        $yourname     = $request->input('yourname');//真实姓名
        $timestamp    = $request->input('timestamp');//随机时间戳
        $securitycode = $request->input('code');
        $sign         = $request->input('sign');
        $params       = [
            'code'      => $securitycode,
            'deviceid'  => $deviceid,
            'mobile'    => $mobile,
            'yourname'  => $yourname,
            'timestamp' => $timestamp,
            'sign'      => $sign
        ];
        $v            = Validator::make($params, $rules, $messages);
        if ($v->fails()) {
            return response()->json(['status' => false, 'code' => $v->messages()->first()]);
        }

        if ($this->checkSign($params) != true) {
            return response()->json(['message' => $result, 'code' => '1007']);
        }

        //验证校验码是否正确
        $mobileCode = EntMobileCode::select('ID')->where('Mobile', $mobile)
            ->where('States', 1)
            ->where('Code', $securitycode)
            ->first();
        if (!$mobileCode) {
            return response()->json(['message' => $result, 'code' => '3001']);
        }


        $checkMemberInfo = EntMemberInfo::select('MemNumber', 'UserName')
            ->where('DeleteMark', '1')
            ->where('UserName', $mobile)
            ->first();

        if ($checkMemberInfo) {
            return response()->json(['message' => $result, 'code' => '3002']);
        }
        $i         = 0;
        $MemNumber = date('Ymd', time()) . '0' . mt_rand();
        while ($i == 0) {
            $checkNumber = EntMemberInfo::select('UserName')->where('MemNumber', $MemNumber)->first();
            if ($checkNumber) {
                $MemNumber = date('Ymd', time()) . '0' . mt_rand();
            } else {
                $i = 1;
            }
        }

        $loginKey                    = md5(date('YmdHis', time()));
        $entMemberInfo               = new EntMemberInfo();
        $entMemberInfo->States       = 0;
        $entMemberInfo->MemNumber    = $MemNumber;
        $entMemberInfo->UserName     = $mobile;
        $entMemberInfo->YourName     = $yourname;
        $entMemberInfo->UserPassWord = '';
        $entMemberInfo->NickName     = '';
        $entMemberInfo->FilePath1    = '';
        $entMemberInfo->WeiXID       = '';
        $entMemberInfo->VipNumber    = 1;
        $entMemberInfo->MemIntegral  = 0;
        $entMemberInfo->LoginKey     = $loginKey;
        $entMemberInfo->MemEndTime   = '';
        $entMemberInfo->AppKey       = $deviceid;
        $entMemberInfo->RegisterType = 3;
        $entMemberInfo->DeleteMark   = 1;
        $entMemberInfo->ReleaseDate  = date('Y-m-d H:i:s', time());
        $entMemberInfo->AddDate      = date('Y-m-d H:i:s', time());
        $entMemberInfo->save();
        if ($entMemberInfo) {
            EntMobileCode::where('Mobile', $mobile)->where('States', 1)->delete();

            return response()->json(['message' => 'ok', 'key' => $entMemberInfo->MemNumber, 'mobile' => $mobile, 'code' => '200']);
        } else {
            return response()->json(['message' => $result, 'code' => '3004']);
        }
    }


    /**
     * 用户注册 微信用户注册只是在内容进行，并不提供给外的API
     * */
    public function wx_register(Request $request)
    {
        $apiData = new ApiData();
        if (empty($request->input('wxUnionid', ''))) {
            $apiData->code    = "201";
            $apiData->message = "缺少微信unionid";

            return $apiData->send();
        }

        $request->offsetSet('yourName', $request->input('NickName'));
        $result = $this->register_action($request);
        if ($result == true) {
            $apiData->code    = "200";
            $apiData->message = "注册成功";
        } else {
            $apiData->code    = "4001";
            $apiData->message = "注册失败";
        }

        return $apiData;
    }


    /**
     * 手机注册
     *
     * */
    public function mobile_register_v3(Request $request)
    {

        $mobile     = $request->input('mobile');
        $mobileCode = $request->input('mobileCode');
        $yourName   = $request->input('yourName');
        $appKey     = $request->input('appKey');
        $apiData    = new ApiData();
        //$apiData->set_data("codeDesc","2001:手机号为空;2002;用户名为空;2003：验证码为空;2004:设备ID为空");
        $rules = [
            'mobile'     => [$mobile, "手机号为空", "2001"],
            'yourname'   => [$yourName, "用户名为空", "2002"],
            'mobilecode' => [$mobileCode, "验证码为空", "2003"],
            'appKey'     => [$appKey, "设备ID为空", "2004"]
        ];

        $result = $this->check_params($rules);
        if ($result->status == false) {
            $apiData->message = $result->message;
            $apiData->code    = $result->code;

            return $apiData->send();
        }

        //1.验证校验码是否正确
        $messageModel = new MobileMassege();
        $result       = $messageModel->check_valid_code($mobile, $mobileCode);

        //return [$result,$mobile,$mobileCode];
        if ($result !== true) {
            $apiData->code    = "3001";
            $apiData->message = "验证码错误";

            return $apiData->send();
        }

        //2.检查用户是否注册
        $memberModel = new MemberModel();
        $memberInfo  = $memberModel->get_member_info_by_mobile($mobile);
        if ($memberInfo != false) {
            $apiData->code    = "3002";
            $apiData->message = "该用户已经注册";

            return $apiData->send();
        }

        $result = $this->register_action($request);

        if (!$result) {
            $apiData->code    = "3004";
            $apiData->message = "注册失败，请将信息填写完毕";

            return $apiData->send();
        }

        $messageModel->delete_code($mobile, $mobileCode);
        $apiData->code    = "200";
        $apiData->message = "注册成功";
        $drpModel         = new DrpModel();
        $userInfo         = $memberModel->get_member_info_by_mobile($mobile);
        $drpInfo          = $drpModel->get_drp_info_by_member_number($userInfo->MemNumber);
        $isDrp            = $drpInfo ? 1 : 0;

        $userInfo->isDrp        = $isDrp;
        $userInfo->mobile       = $userInfo->UserName;
        $userInfo->drpNoticeUrl = "";
        $userId                 = $userInfo->UserID;
        $msgModel               = new MessageModel();
        $token                  = "123456";                                  //token
        $tags                   = $memberModel->get_member_tags($userId);
        $unReadMsgNumber        = $msgModel->get_unreaded_message_number($userId);
        $apiData->set_data('tags', $tags)//用户标签
        ->set_data("token", $token)
            ->set_data('alias', $userInfo->UserName)
            ->set_data('unReadMsgNum', $unReadMsgNumber)
            ->set_data('memberInfo', $userInfo);   //未读信息; //用户别名

        return $apiData->send();
    }


    /**
     * 注册实际操作
     * */
    public function register_action(Request $request)
    {


        $data = [
            "MemNumber"    => create_member_number(),
            "UserName"     => $request->input('mobile', ''),
            "NickName"     => $request->input('yourName', ''),
            "YourName"     => $request->input('yourName', ''),
            "RegisterType" => $request->input('registerType'),
            'AppKey'       => $request->input('appKey', ''),
            "wx_unionid"   => $request->input('wxUnionid', ''),
            'app_openid'   => $request->input('appOpenid', ''),
            'head_img'     => $request->input('headImg', ''),
            'sex'          => $request->input('sex', 'N'),
            'DeleteMark'   => 1
        ];

        $drpModel = new DrpModel();
        $memberId = $drpModel->register($data);
        $parentId = $request->input('parentId');

        if ($parentId) { //获取学习官信息
            $drpInfo = [
                'ParentID'  => $parentId,
                'MemNumber' => $data['MemNumber'],
                'DRPLevel'  => 2
            ];
            $result  = $drpModel->add_drp_student($drpInfo);
        }

        return true;
    }


    /*
     *
     * */
    public function update_member_info(Request $request)
    {

        $userId  = $request->input('userId');
        $appKey  = $request->input('key');
        $apiData = new ApiData();

        $params = [
            'userId' => [$userId, '缺少用户ID', '2001'],
            'appKey' => [$appKey, '缺少设备ID', '2002']
        ];

        $checkResult = $this->check_params($params);
        if ($checkResult->status == false) {
            $apiData->message = $checkResult->message;
            $apiData->code    = $checkResult->code;
        }

        $memberModel = new MemberModel();
        $memberInfo  = $memberModel->get_member_info_by_id($userId);
        if ($memberInfo == false) {
            $apiData->message = "用户不存在";
            $apiData->code    = "3056";

            return $apiData->send();
        }

        $colum    = ['UserName', 'YourName', 'NickName', 'app_openid', 'company_id', 'mobileCode'];
        $data     = ['UserID' => $userId];
        $userInfo = $request->input('userInfo');
        if ($userInfo) {

            $clientType = $request->header('Client-type', '');
            if ($clientType) {
                $userInfo = json_decode(urldecode($userInfo));
            } else {
                (String)$userInfo = $userInfo;
                $userInfo = json_decode($userInfo);
            }

            foreach ($userInfo as $key => $v) {
                if (in_array($key, $colum)) {
                    $data[$key] = $v;
                }
            }
        }

        if (isset($data['UserName'])) { //如果包含有手机号码,则需要验证

            if ((!isset($data['mobileCode'])) || empty($data['mobileCode'])) {
                $apiData->message = "修改手机号需要验证码";
                $apiData->code    = "3057";

                return $apiData->send();
            }

            $mobileModel = new MobileMassege();
            $result      = $mobileModel->check_valid_code($data['UserName'], $data['mobileCode']);

            if ($result !== true && false) {
                $apiData->message = $result;
                $apiData->code    = "3058";

                return $apiData->send();
            }


            $oldUserInfo = $memberModel->get_member_info_by_mobile($data['UserName']);
            //检查手机号是否被绑定 1.当前手机号为空 2.手机号码被使用
            if (empty($memberInfo->UserName) && $oldUserInfo != false && $oldUserInfo->AppKey != $appKey && $oldUserInfo->AppKey != '') {
                $apiData->message = "手机号已经被绑定";
                $apiData->code    = "3059";

                return $apiData->send();
            }
            unset($data['mobileCode']);


            if ($oldUserInfo != false) {
                if ($oldUserInfo->UserID != $memberInfo->UserID) {

                    //绑定手机号
                    //1.取出新的用户信息


                    //2.修改以前的信息
                    $data['wx_unionid'] = $memberInfo->wx_unionid;
                    $data['app_openid'] = $memberInfo->app_openid;
                    $data['head_img']   = $memberInfo->head_img;
                    $data['UserID']     = $oldUserInfo->UserID;
                    $data['AppKey']     = $appKey;

                    //3.销毁新的信息
                    $oldData               = [];
                    $oldData['UserID']     = $userId;
                    $oldData['DeleteMark'] = 0;
                    $memberModel->update_member_info($oldData);
                }
            }
        }

        $memberModel->update_member_info($data);
        $apiData->message = "修改成功";
        $apiData->code    = "200";

        return $apiData->send();
    }

    public function memberinfoByName(Request $request)
    {
        $phone   = $request->Input('phone');
        $status  = preg_match('/^1[34578]\d{9}/', $phone);
        $apiData = new ApiData();
        if ($status) {//如果是手机号
            $memberInfo = MemberModel::where('UserName', $phone)
                ->select('UserID', 'YourName', 'AppKey')
                ->where('DeleteMark',1)
                ->first();
            if (!$memberInfo) {
                $apiData->message = '用户不存在';
                $apiData->code    = 404;
                $apiData->data    = [];

                return $apiData->send();
            }

            $data = DB::table('use_device_info')->where('user_id', $memberInfo->UserID)
                ->select('open_app_date', 'phone_system', 'app_version')
                ->orderBy('created_at', 'desc')
                ->limit(1)
                ->first();

            $data = $data ? get_object_vars($data) : null;


            $apiData->message = '获取用户信息成功';
            $apiData->code    = 200;
            $user             = ['userName' => $memberInfo->YourName, 'AppKey' => $memberInfo->AppKey];
            $data             = $data ? array_merge($user, $data) : $user;

            $apiData->data = $data;

            return $apiData->send();
        }
        $apiData->code    = 404;
        $apiData->message = '手机格式错误';

        return $apiData->send();
    }


    public function clearAppkey(Request $request)
    {
        $phone    = $request->Input('phone');
        $user_num = $request->Input('num');//执行用户的编号
        $status   = preg_match('/^1[34578]\d{9}/', $phone);
        $apiData  = new ApiData();
        if ($status) {//如果是手机号
            $memberInfo = MemberModel::where('UserName', $phone)
                ->where('DeleteMark',1)
                ->update(['AppKey' => null]);
            if (!$memberInfo) {
                $apiData->message = '清除用户key失败';
                $apiData->code    = 404;
                $apiData->data    = [];

                return $apiData->send();
            }

            //1.未完成缺少记录用户的操作
            $now = Carbon::now();
            DB::table('clear_appkey_log')->insert(['user_info' => $user_num, 'created_at' => $now, 'updated_at' => $now]);

            $apiData->message = '清除用户key成功';
            $apiData->code    = 200;
            $apiData->data    = [];

            return $apiData->send();
        }
        $apiData->code    = 404;
        $apiData->message = '手机格式错误';

        return $apiData->send();
    }

}









